#include "resourceeditorveto.h"

#include "../documents/data/graphicdata.h"

#include <gdmodelquerymaker.h>
#include <ieditoritem.h>

using namespace core;
using namespace swp;

ResourceEditorVeto::ResourceEditorVeto(IGraphicEditorItem *item) :
    IVetoObject(),
    m_item(item)
{

}

bool ResourceEditorVeto::valueChanged(const QString& propertyName,
    const QString& propertyText, const QVariant &oldValue,
    const QVariant &newValue, QString& reason) const
{
    bool ret = true;

    GraphicData* data = m_item != 0 ? dynamic_cast<GraphicData*>(
        m_item->parentDocumentData()) : 0;

    if (data != 0)
    {
        GDModelQueryMaker queryMaker(*data);

        const QList<int> types = queryMaker.getTypes();

        foreach (const int& type, types)
        {
            const QList<IGraphicEditorItem*> items =
                queryMaker.getItems(type);

            foreach (IGraphicEditorItem* item, items)
            {
                if (item->propertyValue(propertyName) == newValue)
                {
                    reason = QObject::tr("Item with this %1 is already "
                        "present in the document").arg(propertyText);
                    ret = false;
                    break;
                }
            }

            if (!ret)
            {
                break;
            }
        }
    }

    return ret;
}
